package me.leiusual.sharing.ui.order

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import kotlinx.android.synthetic.main.fragment_order_detail.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.orderdetail.Model
import me.leiusual.sharing.api.model.orderdetail.OrderDetail
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.base.AbstractFragment
import me.leiusual.sharing.ui.base.AbstractViewModel
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.order.adapter.OrderDetailAdapter
import me.leiusual.sharing.ui.order.adapter.OrderDetailInvoiceAdapter
import me.leiusual.sharing.util.extension.toSpanned
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-31
 * description:
 */
class OrderDetailFragment : AbstractFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: OrderDetailViewModel by viewModels { factory }

  override val abstractViewModel: AbstractViewModel
    get() = viewModel

  private val args: OrderDetailFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_order_detail, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    button_pay.setOnClickListener(this)
    button_delete.setOnClickListener(this)
    button_confirm.setOnClickListener(this)

    recycler_view_invoice.adapter = OrderDetailInvoiceAdapter {
      Timber.v("点击：%s", it)

      val navDirections = OrderDetailFragmentDirections.actionOrderDetailFragmentToOrderLogisticsFragment(it.expressNumber, it.expressCode)
      findNavController().navigate(navDirections)
    }

    recycler_view.adapter = OrderDetailAdapter()

    observeData()
    viewModel.orderDetail(args.storeId, args.code)
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.button_pay -> {
        val data = viewModel.orderDetail.value as? Data.Success
        data?.data?.model?.code?.let {
          viewModel.orderRePay(it)
        }
      }
      R.id.button_delete -> {
        val data = viewModel.orderDetail.value as? Data.Success
        data?.data?.model?.code?.let {
          viewModel.orderDelete(it)
        }
      }
      R.id.button_confirm -> {
        val data = viewModel.orderDetail.value as? Data.Success
        data?.data?.model?.code?.let {
          viewModel.orderConfirm(it)
        }
      }
    }
  }

  private fun observeData() {
    viewModel.orderDetail.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderDetail = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          doUpdateViews(it.data)
        }
      }
    })

    viewModel.orderRePay.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderRePay = %s", it)
      when (it) {
        is Data.Loading -> {
          button_pay.isEnabled = false
        }
        is Data.Error -> {
          button_pay.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_pay.isEnabled = true

          // 去支付
          val data = viewModel.orderDetail.value as? Data.Success
          when (data?.data?.model?.payMode) {
            "WX_PAY" -> doPayByWeChat(it.data)
            "ALI_PAY" -> doPayByAlipay(it.data)
          }
        }
      }
    })

    viewModel.orderConfirm.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderConfirm = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_confirm.isEnabled = true
          toast("确认成功")
          findNavController().popBackStack()
        }
      }
    })

    viewModel.orderDelete.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("orderDelete = %s", it)
      when (it) {
        is Data.Loading -> {
          button_delete.isEnabled = false
        }
        is Data.Error -> {
          button_delete.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_delete.isEnabled = true
          toast("删除成功")
          findNavController().popBackStack()
        }
      }
    })
  }

  private fun doUpdateViews(data: OrderDetail) {

    // 订单详情
    val builder = StringBuilder()
    builder.append("""订单编号：${data.model.code}""")
    builder.append("""<br/>收货地址：${data.model.fullAddress}""")
    builder.append("""<br/>联系电话：${data.model.contactPhone}""")
    builder.append("""<br/>下单时间：${data.model.deliveryTime ?: "-"}""")
    builder.append("""<br/>交易时间：${data.model.deliveryTime ?: "-"}""")
    builder.append("""<br/>买家留言：${data.model.memo ?: "-"}""")
    text_view_detail.text = builder.toString().toSpanned()

    // 订单状态
    text_view_status.text = """订单状态：${data.model.orderStatusStr}"""
    if (data.model.deliveryStatus in arrayOf(Model.DELIVERY_STATUS_CONFIRMING, Model.DELIVERY_STATUS_CONFIRMED)) {
      text_view_status.text = """订单状态：${data.model.deliveryStatusStr}"""
    }

    // 操作按钮
    when (data.model.orderStatus) {
      Model.ORDER_STATUS_PAYING -> {
        button_pay.isVisible = true
      }
      Model.ORDER_STATUS_CANCELLED -> {
        button_delete.isVisible = true
      }
      Model.ORDER_STATUS_PAID -> {
        if (args.storeId == 0L && data.model.deliveryStatus == Model.DELIVERY_STATUS_CONFIRMING) {
          button_confirm.isVisible = true
        }
      }
      else -> {
        button_pay.isVisible = false
        button_delete.isVisible = false
        button_confirm.isVisible = false
      }
    }

    // 物流信息
    if (data.invoices.isEmpty()) {
      recycler_view_invoice.isVisible = false
    } else {
      recycler_view_invoice.isVisible = true

      val adapter = recycler_view_invoice.adapter as OrderDetailInvoiceAdapter
      adapter.submitList(data.invoices)
    }

    // 订单商品
    val adapter = recycler_view.adapter as OrderDetailAdapter
    adapter.submitList(data.model.orderDetails)

    // 订单合计
    text_view_total.text = """合计：￥${data.model.amount}"""
  }
}